package com.kaikeba.filter;

import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import java.util.Arrays;
import java.util.List;

/**
 * 局部过滤器
 */
@Component
public class MyParamGatewayFilterFactory extends AbstractGatewayFilterFactory<MyParamGatewayFilterFactory.Config> {


    static final String PARAM_NAME = "param";

    public MyParamGatewayFilterFactory() {
        super(Config.class);
    }


    public List<String> shortcutFieldOrder() {
        //对应内部类config中的属性param ，读取参数（例：name）
        return Arrays.asList(PARAM_NAME);
    }

    @Override
    public GatewayFilter apply(Config config) {
        return (exchange,chain)-> {
            ServerHttpRequest request = exchange.getRequest();
            //以键值对的形式来存储 例:<name,xxx>
            if (request.getQueryParams().containsKey(config.param)){
                    request.getQueryParams().get(config.param).forEach(value -> {
                        System.out.printf("---局部过滤器--- %s   =  %s",config.param,value);
                            }
                    );
            }
            //放行
            return chain.filter(exchange);
        };
    }


    public static class Config{
        //对应在配置过滤器的时候指定的参数名
        private String param;

        public String getParam() {
            return param;
        }

        public void setParam(String param) {
            this.param = param;
        }
    }

}
